<template>
  <div class="court-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>场地管理</span>
        </div>
      </template>
      <div class="content-body">
        <!-- 搜索和筛选区域 -->
        <div class="search-filter">
          <el-input 
            v-model="queryForm.name" 
            placeholder="请输入场地名称搜索"
            style="width: 200px; margin-right: 10px;"
            prefix-icon="Search"
            clearable
          />
          <el-select v-model="queryForm.status" placeholder="选择状态" style="width: 120px; margin-right: 10px;">
            <el-option label="全部" value="" />
            <el-option label="可用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleAddCourt">新增场地</el-button>
        </div>
        
        <!-- 场地列表 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="id" label="场地ID" width="80" />
          <el-table-column label="场地图片" width="120">
            <template #default="scope">
              <el-image 
                v-if="scope.row.image"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                style="width: 80px; height: 50px; border-radius: 4px;"
              />
              <span v-else>暂无</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="场地名称" width="120" />
          <el-table-column prop="address" label="地址" width="200" />
          <el-table-column prop="placeType" label="场地类型" width="100" />
          <el-table-column prop="num" label="数量" width="80" />
          <el-table-column prop="price" label="价格(元/小时)" width="120" />
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-switch v-model="row.status" active-value="1" inactive-value="0" />
            </template>
          </el-table-column>
          <el-table-column prop="phoneNo" label="联系方式" width="150" />
          <el-table-column label="设施" width="200">
            <template #default="scope">
              <el-tag 
                v-for="(facility, index) in (scope.row.facilities ? scope.row.facilities.split(',').filter(f => f.trim()) : [])" 
                :key="index"
                size="small"
                style="margin-right: 5px;"
              >
                {{ facility }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditCourt(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDeleteCourt(scope.row.id)"
                v-if="!isDeleting"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination 
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑场地弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="700px"
      @close="resetForm"
    >
      <el-form 
        ref="courtFormRef" 
        :model="courtForm" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="courtForm.name" placeholder="请输入场地名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="courtForm.address" placeholder="请输入场地地址" />
        </el-form-item>
        <el-form-item label="场地类型" prop="placeType">
          <el-select v-model="courtForm.placeType" placeholder="请选择场地类型">
            <el-option label="硬地" value="硬地" />
            <el-option label="红土" value="红土" />
            <el-option label="草地" value="草地" />
          </el-select>
        </el-form-item>
        <el-form-item label="场地数量" prop="num">
          <el-input-number 
            v-model="courtForm.num" 
            :min="1" 
            :step="1" 
            placeholder="请输入场地数量"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="courtForm.price" 
            :min="0" 
            :step="10" 
            placeholder="请输入每小时价格"
          />
        </el-form-item>
        <el-form-item label="开放时间" prop="openingHours">
          <el-input v-model="courtForm.openingHours" placeholder="如：09:00-22:00" />
        </el-form-item>
        <el-form-item label="设施" prop="facilities">
          <el-select v-model="courtForm.facilities" placeholder="请选择设施" multiple>
            <el-option label="休息区" value="休息区" />
            <el-option label="卫生间" value="卫生间" />
            <el-option label="储物柜" value="储物柜" />
            <el-option label="淋浴室" value="淋浴室" />
            <el-option label="饮用水" value="饮用水" />
          </el-select>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input-number 
            v-model="courtForm.longitude" 
            :min="0" 
            :step="0.0001" 
            placeholder="请输入经度"
          />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input-number 
            v-model="courtForm.latitude" 
            :min="0" 
            :step="0.0001" 
            placeholder="请输入纬度"
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNo">
          <el-input v-model="courtForm.phoneNo" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="场地图片" prop="image">
          <el-upload
            class="image-upload"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleImageUploadSuccess"
            :on-error="handleImageUploadError"
            :before-upload="beforeImageUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <div v-if="!courtForm.image">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽图片到此处或 <em>点击上传</em>
              </div>
            </div>
            <div v-else class="image-preview">
              <img 
                :src="courtForm.image" 
                alt="场地图片" 
                class="uploaded-image"
              >
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="removeImage"
              >
                删除图片
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="courtForm.remarks" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, ElSwitch, ElImage } from 'element-plus'
import { Search, UploadFilled } from '@element-plus/icons-vue'
import { nearbyPlacesList,nearbyPlacesAdd,nearbyPlacesDelete,nearbyPlacesUpdate } from '@/request/nearbyplaces.js'

// 上传配置
const uploadUrl = '/api/system/file/uploadFile'
const uploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}

const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: ''
})

const isDeleting = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增场地')
const courtFormRef = ref(null)
const editingCourtId = ref(null)

const tableData = ref([])
const total = ref(0)

const getList=()=>{
  nearbyPlacesList(queryForm.value).then(res=>{
    tableData.value = res.records
    total.value = res.total
    // 处理图片URL格式
    tableData.value.forEach(item => {
      if (item.image) {
        // 检查是否已经包含/api前缀或是否是完整的URL
        if (!item.image.startsWith('/api') && !item.image.startsWith('http://') && !item.image.startsWith('https://')) {
          // 只在需要时添加/api前缀
          item.image = "/api" + item.image
        }
      }
    })
  })
}
getList()

// 场地表单
const courtForm = reactive({
  name: '',
  address: '',
  placeType: '',
  num: null, // 新增场地数量字段
  price: null,
  openingHours: '',
  facilities: [],
  longitude: null,
  latitude: null,
  remarks: '',
  image: '', // 改为单个图片URL
  phoneNo: '' // 新增联系方式字段
})


// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入场地名称', trigger: 'blur' },
    { min: 2, max: 50, message: '场地名称长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入场地地址', trigger: 'blur' },
    { min: 5, max: 200, message: '地址长度应在 5 到 200 个字符之间', trigger: 'blur' }
  ],
  placeType: [
    { required: true, message: '请选择场地类型', trigger: 'change' }
  ],
  num: [
    { required: true, message: '请输入场地数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '场地数量至少为1', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  openingHours: [
    { required: true, message: '请输入开放时间', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { type: 'number', min: -180, max: 180, message: '经度范围应为 -180 到 180', trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { type: 'number', min: -90, max: 90, message: '纬度范围应为 -90 到 90', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传场地图片', trigger: 'change' }
  ],
  phoneNo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  if (courtFormRef.value) {
    courtFormRef.value.resetFields()
  }
  editingCourtId.value = null
  Object.keys(courtForm).forEach(key => {
    courtForm[key] = key === 'facilities' ? [] : ''
    if (key === 'price' || key === 'longitude' || key === 'latitude' || key === 'num') {
      courtForm[key] = null
    }
  })
}

// 图片上传成功
const handleImageUploadSuccess = (response, file) => {
  console.log('图片上传响应:', response)
  if (response && response.data) {
    // 检查响应中的数据是否已经包含/api前缀
    if (typeof response.data === 'string' && !response.data.startsWith('/api') && !response.data.startsWith('http')) {
      // 只在需要时添加/api前缀
      courtForm.image = '/api' + response.data
    } else {
      courtForm.image = response.data
    }
  } else {
    // 创建本地URL用于预览，但实际提交时会进行检查
    courtForm.image = URL.createObjectURL(file.raw)
  }
  console.log('当前courtForm:', courtForm)
  ElMessage.success('图片上传成功')
}

// 图片上传失败
const handleImageUploadError = (error) => {
  ElMessage.error('图片上传失败')
}

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 删除图片
const removeImage = () => {
  courtForm.image = ''
}


// 新增场地
const handleAddCourt = () => {
  dialogTitle.value = '新增场地'
  resetForm()
  dialogVisible.value = true
}

// 编辑场地
const handleEditCourt = (court) => {
  dialogTitle.value = '编辑场地'
  editingCourtId.value = court.id
  // 复制场地数据到表单，并转换数字类型字段
  Object.keys(courtForm).forEach(key => {
    if (key === 'price' || key === 'longitude' || key === 'latitude' || key === 'num') {
      // 将字符串转换为数字
      courtForm[key] = Number(court[key]) || 0
    } else if (key === 'facilities') {
      // 将逗号分隔的字符串转换为数组
      courtForm[key] = court[key] ? court[key].split(',').filter(f => f.trim()) : []
    } else if (key === 'image') {
      // 处理图片URL，确保格式正确，避免重复添加/api前缀
      if (court[key]) {
        // 检查是否已经包含/api前缀
        if (court[key].startsWith('/api')) {
          courtForm[key] = court[key]
        } else {
          // 检查是否是完整的URL (以http开头)
          if (court[key].startsWith('http://') || court[key].startsWith('https://')) {
            courtForm[key] = court[key]
          } else {
            // 添加/api前缀
            courtForm[key] = '/api' + court[key]
          }
        }
      } else {
        courtForm[key] = ''
      }
    } else {
      courtForm[key] = court[key]
    }
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  courtFormRef.value.validate((valid) => {
    if (valid) {
      // 提交时检查
      if (!courtForm.image) {
        ElMessage.error('请上传场地图片！')
        return
      }
      
      // 创建提交表单数据的副本，避免直接修改原表单
      const submitData = { ...courtForm }
      
      // 处理图片URL格式
      if (submitData.image) {
        // 如果URL以/api开头，移除前缀
        if (submitData.image.startsWith('/api')) {
          submitData.image = submitData.image.substring(4)
        }
        // 如果是完整的URL (以http开头)，需要特殊处理
        else if (submitData.image.startsWith('http://') || submitData.image.startsWith('https://')) {
          // 如果是本地预览URL (blob:)，则忽略（不应该在提交时出现）
          if (submitData.image.startsWith('blob:')) {
            ElMessage.error('图片尚未上传完成，请稍候重试！')
            return
          }
          // 对于其他完整URL，可能需要后端支持特殊处理，这里先保留
          // 实际项目中可能需要根据后端API要求进行调整
        }
      }
      
      // 将设施数组转换为逗号分隔的字符串
      if (submitData.facilities && Array.isArray(submitData.facilities)) {
        submitData.facilities = submitData.facilities.join(',')
      }
      
      if (editingCourtId.value) {
        submitData.id = editingCourtId.value
        // 编辑模式
        nearbyPlacesUpdate(submitData).then(res => {
          ElMessage.success('场地更新成功')
          dialogVisible.value = false
          resetForm()
          getList()
        })
      } else {
        // 新增模式
        submitData.status = '1' // 默认可用状态
        // 调用新增接口
        nearbyPlacesAdd(submitData).then(res => {
          ElMessage.success('场地添加成功')
          dialogVisible.value = false
          resetForm()
          getList()
        })
      }
    }
  })
}




// 切换场地状态
const handleToggleStatus = (court) => {
  const newStatus = court.status === 'available' ? 'maintenance' : 'available'
  const index = tableData.value.findIndex(c => c.id === court.id)
  if (index !== -1) {
    tableData.value[index].status = newStatus
    ElMessage.success(`${court.name} 状态已切换为${getStatusText(newStatus)}`)
  }
}

// 删除场地
const handleDeleteCourt = (id) => {
  ElMessageBox.confirm('确定要删除这个场地吗？删除后无法恢复。', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isDeleting.value = true
    nearbyPlacesDelete(id).then(res => {
      ElMessage.success('场地删除成功')
      isDeleting.value = false
      getList()
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 分页相关方法
const handleSizeChange = (size) => {
  queryForm.value.pageSize = size
  ElMessage.info(`每页显示 ${size} 条数据`)
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.value.pageNum = current
  ElMessage.info(`当前页码: ${current}`)
  getList()
}
</script>

<style scoped>


.content-body {
  padding-top: 10px;
}

.search-filter {
  display: flex;
  align-items: center;
}

.image-preview {
  margin-top: 10px;
}

.image-preview h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #606266;
}

/* 限制上传图片的大小 */
.uploaded-image {
  max-width: 300px;
  max-height: 200px;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 4px;
}

.image-upload {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>